package com.dm0858.bianmin.mine.fragment;


import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.bumptech.glide.Glide;
import com.dm0858.bianmin.R;
import com.dm0858.bianmin.app.MyApp;
import com.dm0858.bianmin.databinding.FragmentMineBinding;
import com.dm0858.bianmin.mine.activity.BindPhoneActivity;
import com.dm0858.bianmin.mine.activity.LoginActivity;
import com.dm0858.bianmin.mine.activity.PlatformConstructionActivity;
import com.dm0858.bianmin.mine.activity.ProxyActivity;
import com.dm0858.bianmin.mine.adapter.MineRecyclerViewAdapter;
import com.dm0858.bianmin.mine.base.BaseFragment;
import com.dm0858.bianmin.mine.bean.Item;
import com.dm0858.bianmin.mine.listener.IWXLoginListener;
import com.dm0858.bianmin.mine.tools.DialogUtils;
import com.dm0858.bianmin.mine.tools.LogUtils;
import com.dm0858.bianmin.mine.tools.SPUtils;
import com.dm0858.bianmin.mine.tools.ToastUtils;
import com.dm0858.bianmin.mine.viewmodel.MineViewModel;
import com.mob.MobSDK;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import butterknife.ButterKnife;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * @author 迪迪丶Sir
 * @description 我的页面
 * @e-mail asd969709719@qq.com
 * @since 2020-04-29
 **/
public class MineFragment extends BaseFragment implements View.OnClickListener{

    private FragmentMineBinding binding;

    private MineViewModel viewModel;

    private MineRecyclerViewAdapter adapter;

    private List<Item> items;

    private String unionid = "";

    //item名字
    private String[] titles = new String[]{
            "资质认证","资质查询","我的发布","帖子管理","我的收藏"
    };

    private int[] icons = new int[]{
            R.drawable.ic_certification_24dp,
            R.drawable.ic_query_24dp,
            R.drawable.ic_release_24dp,
            R.drawable.ic_post_manage_24dp,
            R.drawable.ic_my_collect_24dp

    };

    @Override
    protected View initView() {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_mine, container, false);
        binding.setOnClick(this);
//        if (!MyApp.userid.equals("")) binding.txtRegister.setVisibility(View.INVISIBLE);
        return binding.getRoot();
    }

    @Override
    protected void initData() {
        viewModel = new ViewModelProvider(this).get(MineViewModel.class);
        LogUtils.d(MyApp.openid);
        viewModel.userInfo();
        //设置头像
        viewModel.getAvatar().observe(this, s -> {
            if ("".equals(s)) Glide.with(mContext).load(R.drawable.img_avatar).into(binding.imgAvatar);
            else Glide.with(mContext).load(s).into(binding.imgAvatar);
        });
        //设置昵称
        viewModel.getNickName().observe(this,s ->{
            if (s.equals("")) binding.txtLogin.setText(MyApp.phone);
            else binding.txtLogin.setText(s);
        });
        setData();
        setRecyclerView();
        initShareSdk();

    }

    private void setRecyclerView() {
        if (adapter == null) adapter = new MineRecyclerViewAdapter(mContext,R.layout.adapter_mine_item_layout,items);
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        binding.recyclerview.setLayoutManager(layoutManager);
        binding.recyclerview.setAdapter(adapter);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    private void setData() {
        if (items == null) items = new ArrayList<>();
        for (int i = 0,len = titles.length;i < len;i++) {
            Item item = new Item(titles[i],icons[i]);
            items.add(item);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_avatar:
            case R.id.txt_login:
                switch (MyApp.launchMode) {
                    case -1:
                        startActivityForResult(new Intent(mContext, LoginActivity.class),10000);
                        break;
                    case 1:
                    case 2:
                        DialogUtils.showTipDialog(mContext, "退出登录", "确定退出登录吗？", new DialogUtils.onClickListener() {
                            @Override
                            public void negativeClick() {

                            }

                            @Override
                            public void positiveClick() {
                                SPUtils.getInstance("user_info").clear();
                                viewModel.setNickName("账号/微信登录");
                                MyApp.userid = "";
                                MyApp.phone = "";
                                MyApp.openid = "";
                                MyApp.launchMode = -1;
                                SPUtils.getInstance("user_info").put("userid",MyApp.userid,true);
                                SPUtils.getInstance("user_info").put("phone",MyApp.phone,true);
                                SPUtils.getInstance("user_info").put("openid",MyApp.openid,true);
                                SPUtils.getInstance("user_info").put("launchMode",MyApp.launchMode,true);
                                Glide.with(mContext).load(R.drawable.img_avatar).into(binding.imgAvatar);
                            }

                            @Override
                            public void cancelClick() {

                            }

                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        });
                        break;
                }





                break;
            case R.id.txt_platformConstruction:
                startActivity(new Intent(mContext, PlatformConstructionActivity.class));
                break;
            case R.id.txt_actingAsAnAgent:
                startActivity(new Intent(mContext, ProxyActivity.class));
                break;
            case R.id.txt_circleOfFriends:
                showShare(WechatMoments.NAME);
                break;
            case R.id.txt_weChatOfFriends:
                showShare(Wechat.NAME);
                break;
            case R.id.txt_qq:
                showShare(QQ.NAME);
                break;
            case R.id.txt_more:
                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.putExtra(Intent.EXTRA_STREAM, "imageUri");
                shareIntent.setType("image/*");
                startActivity(Intent.createChooser(shareIntent, "分享到"));
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10000) {
            if (resultCode == 10001) {
                Bundle bundle = data.getExtras();
                viewModel.setAvatar(bundle.getString("headimgurl"));
                viewModel.setNickName(bundle.getString("nickname"));
                MyApp.openid = bundle.getString("openid","");
                unionid = bundle.getString("unionid","");

                viewModel.wxLogin( MyApp.openid, viewModel.getNickName().getValue(), unionid, viewModel.getAvatar().getValue(), new IWXLoginListener() {

                    @Override
                    public void bind() {
                        //微信登录切绑定了手机
                        MyApp.launchMode = 1;
                        SPUtils.getInstance("user_info").put("openid", MyApp.openid,true);
                        SPUtils.getInstance("user_info").put("launchMode",MyApp.launchMode,true);
                        ToastUtils.showShort("登录成功");
                    }

                    @Override
                    public void unBind() {
                        MyApp.launchMode = 2;
                        SPUtils.getInstance("user_info").put("openid", MyApp.openid,true);
                        SPUtils.getInstance("user_info").put("launchMode",MyApp.launchMode,true);
                        DialogUtils.showTipDialog(mContext, "绑定手机号", "您还未绑定手机号，是否需要绑定？", new DialogUtils.onClickListener() {
                            @Override
                            public void negativeClick() {
                                save();
                            }

                            @Override
                            public void positiveClick() {

                                Bundle b = new Bundle();
                                b.putString("openid", MyApp.openid);
                                Intent intent = new Intent(mContext,BindPhoneActivity.class);
                                intent.putExtras(b);
                                startActivity(intent);
                            }

                            @Override
                            public void cancelClick() {
                                save();
                            }

                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                ToastUtils.showShort("333");
                            }
                        });
                    }
                });
            }
            else if (resultCode == 10002) {
                viewModel.userInfo();
                if (viewModel.getAvatar().getValue().equals("")){
                    Glide.with(mContext).load(R.drawable.img_avatar).into(binding.imgAvatar);
                }
                if (viewModel.getNickName().getValue().equals("")) {
                    binding.txtLogin.setText(MyApp.phone);
                }
            }
        }
    }

    private void save() {
        SPUtils.getInstance("user_info").put("userid", "",true);
        SPUtils.getInstance("user_info").put("phone", "",true);
    }

    /**
     * 
     * @description 是否同意隐私协议
     * @author 迪迪丶Sir
     * @e-mail asd969709719@qq.com
     * @since 2020-05-04
     **/
    private void initShareSdk() {
        MobSDK.submitPolicyGrantResult(true, null);
    }

    private void showShare(String platform) {
        final OnekeyShare oks = new OnekeyShare();
        //指定分享的平台，如果为空，还是会调用九宫格的平台列表界面
        if (platform != null) {
            oks.setPlatform(platform);
        }
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle("便民生活服务");
        // titleUrl是标题的网络链接，仅在Linked-in,QQ和QQ空间使用
//        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("便民生活，服务有我");
        //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
        oks.setImageUrl(SPUtils.getInstance("user_info").getString("avatar",""));
        // url仅在微信（包括好友和朋友圈）中使用
        if (platform.equals(WechatMoments.NAME) || platform.equals(Wechat.NAME))
            oks.setUrl("http://bmshfw.net/down.html");
        else if (platform.equals(QQ.NAME))
            oks.setTitleUrl("http://bmshfw.net/down.html");

        oks.setCallback(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                ToastUtils.showShort("分享成功");
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                ToastUtils.showShort("分享失败");
            }

            @Override
            public void onCancel(Platform platform, int i) {
                ToastUtils.showShort("分享取消");
            }
        });
        //启动分享
        oks.show(MobSDK.getContext());
    }
}
